package com.ruoyi.framework.security.filter;

import com.ruoyi.common.utils.jwt.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
public class TokenFilter extends OncePerRequestFilter {

    private static final String[] FILTER_PATHS = {"/system/info"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        for (String allowedPath : FILTER_PATHS) {
            if (requestURI.matches(allowedPath.replaceAll("\\*", ".*"))) {
                break;          // 继续该过滤器的校验
            }
            return;     // 没匹配到要校验的路径 放行
        }

        // 获取请求头中的 token
        String token = request.getHeader("Authorization");
        System.out.println("My token: " + token);
        if (token == null) {
            // 如果没有 token，则继续链式调用，让后续过滤器处理
            chain.doFilter(request, response);
            return;
        }

        // 解析 token 并获取用户 ID
        Long userId = JWTUtil.getUserid(token);
        System.out.println("userid: " + userId);

        // 如果无法解析用户 ID，则返回未授权状态码
        if (userId != null) {
            // 继续链式调用，让后续过滤器处理
            chain.doFilter(request, response);
        } else {
            // 这里应该设置适当的响应给客户端，表示认证失败
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }
}